
const app = getApp() // 获取app.js这个文件
const util= require('../../utils/util.js') // 导入util.js文件

Page({ 
    data: { 
        item: {},    
        count: 0,    
        buyaddress:'',
        api: app.globalData.api
    },
    
    onLoad: function (options) { // 页面主函数
        
        this.data.item.gname = options.gname
        this.data.item.price = options.price
        this.data.item.detail = options.detail
        this.data.item.amount = options.amount
        this.data.item.uid = options.uid
        this.data.item.gid = options.gid
        this.setData(this.data) 
        
    },
    
    onInput(e) {
        this.data[e.currentTarget.dataset.name] = e.detail.value
        if (e.currentTarget.dataset.name == 'count'
            && isNaN(e.detail.value)) {
            util.alert('请输入数字')
        }
    },
    buy() { // 判空校验 & 合法校验
        if (!this.data.count || isNaN(this.data.count)) { 
            util.alert('请输入数字')
            return
        }
        if(this.data.count > this.data.item.amount){
            util.alert('超出购买数量')
            return
        } 
        var order = {
            uid:wx.getStorageSync('admin'),
            gid:this.data.item.gid,
            buyaddress:this.data.buyaddress,
            count: this.data.count,
            status:0,
            ctime:util.formatTime(new Date())
        }
        
        wx.request({
            url: this.data.api+'/wx/addorder',
            method: 'POST',
            data: order,
            header: {
                'content-Type': 'application/json'
                },
            success:function(res){
                setTimeout(()=>{  
                    wx.redirectTo({
                        url: '../index/index',
                    })
                },2000)
                util.alert('下单成功!') 
            }
        })
    },

})